package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//操作Session资源的控制器
@RestController
@RequestMapping("/sessions")
public class SessionController {
    @Autowired
    private IUserService userService;

    /*
    用户登录的接口
    资源:/Sessions
    动作:POST
    参数:email=xx&password=xx
     */
    @PostMapping
    public Object login(@RequestParam String email, @RequestParam String password) {
        JSONResult result = new JSONResult();
        try {
            //1:调用业务方法登录操作
            User u = userService.login(email, password);
            //2:登录成功,存入session
            UserContext.setCurrentUser(u);
            //3:设置到JSONResult,然后转成JSON返回
            result.setData(u);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /*
    用户注销
    资源:/sessions
    动作:DELETE
    参数:
     */
    @DeleteMapping
    public void logout(HttpSession session, HttpServletResponse resp) {
        //销毁Session即可
        session.invalidate();
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
